<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CustomerForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="客户名称" v-bind="validateInfos.customerName" id="CustomerForm-customerName" name="customerName">
								<a-input v-model:value="formData.customerName" placeholder="请输入客户名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
           <a-col :span="24">
							<a-form-item label="旺店通名称" v-bind="validateInfos.fenxiaoNick" id="CustomerForm-fenxiaoNick" name="fenxiaoNick">
								<a-input v-model:value="formData.fenxiaoNick" placeholder="请输入旺店通名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="旺店通编号" v-bind="validateInfos.distributorCode" id="CustomerForm-distributorCode" name="distributorCode">
								<a-input v-model:value="formData.distributorCode" placeholder="请输入旺店通分销商编号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="客户区域" v-bind="validateInfos.regionId" id="CustomerForm-regionId" name="regionId">
								<j-area-linkage v-model:value="formData.regionId" placeholder="请输入客户区域" saveCode="region"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="客户负责人姓名" v-bind="validateInfos.contactName" id="CustomerForm-contactName" name="contactName">
								<a-input v-model:value="formData.contactName" placeholder="请输入客户负责人姓名"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="负责人手机号" v-bind="validateInfos.contactPhone" id="CustomerForm-contactPhone" name="contactPhone">
								<a-input v-model:value="formData.contactPhone" placeholder="请输入负责人手机号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="负责人微信号" v-bind="validateInfos.wechatId" id="CustomerForm-wechatId" name="wechatId">
								<a-input v-model:value="formData.wechatId" placeholder="请输入负责人微信号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="合作状态" v-bind="validateInfos.status" id="CustomerForm-status" name="status">
								<j-dict-select-tag v-model:value="formData.status" dictCode="cooperation_status" placeholder="请选择合作状态"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="合作开始日期" v-bind="validateInfos.cooperationDate" id="CustomerForm-cooperationDate" name="cooperationDate">
								<a-date-picker placeholder="请选择合作日期"  v-model:value="formData.cooperationDate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="合作结束日期" v-bind="validateInfos.cooperationDateEnd" id="CustomerForm-cooperationDateEnd" name="cooperationDateEnd">
								<a-date-picker placeholder="请选择合作日期"  v-model:value="formData.cooperationDateEnd" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="合作期限" v-bind="validateInfos.cooperationDuringDate" id="CustomerForm-cooperationDuringDate" name="cooperationDuringDate">
								<a-input v-model:value="formData.cooperationDuringDate" placeholder="请输入合作期限"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="行业" v-bind="validateInfos.industry" id="CustomerForm-industry" name="industry">
								<!-- <j-dict-select-tag v-model:value="formData.industry" dictCode="industry" placeholder="请选择行业"  allow-clear /> -->
                	<j-select-multiple type="list_multi" v-model:value="formData.industry" dictCode="industry" placeholder="请选择行业"  :triggerChange="false"/>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="授权渠道" v-bind="validateInfos.authChannel" id="CustomerForm-authChannel" name="authChannel">
								<a-input v-model:value="formData.authChannel" placeholder="请输入客户授权渠道"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="授权企业" v-bind="validateInfos.authCompany" id="CustomerForm-authCompany" name="authCompany">
								<a-input v-model:value="formData.authCompany" placeholder="请输入授权企业"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="合作形式" v-bind="validateInfos.cooperationType" id="CustomerForm-cooperationType" name="cooperationType">
								<a-input v-model:value="formData.cooperationType" placeholder="请输入合作形式"  allow-clear ></a-input>
                
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="合作资料" v-bind="validateInfos.cooperationDocs" id="CustomerForm-cooperationDocs" name="cooperationDocs">
								<!-- <a-input v-model:value="formData.cooperationDocs" placeholder="请输入合作资料"  allow-clear ></a-input> -->
                <j-image-upload :fileMax="0" v-model:value="formData.cooperationDocs" ></j-image-upload>
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="回款方式" v-bind="validateInfos.paymentMethod" id="CustomerForm-paymentMethod" name="paymentMethod">
								<a-input v-model:value="formData.paymentMethod" placeholder="请输入回款方式"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="回款账号" v-bind="validateInfos.paymentAccount" id="CustomerForm-paymentAccount" name="paymentAccount">
								<a-input v-model:value="formData.paymentAccount" placeholder="请输入回款账号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="24">
							<a-form-item label="保证金" v-bind="validateInfos.deposit" id="CustomerForm-deposit" name="deposit">
								<a-input v-model:value="formData.deposit" placeholder="请输入保证金"  allow-clear ></a-input>
							</a-form-item>
						</a-col>            



						<a-col :span="24">
							<a-form-item label="对接销售人员" v-bind="validateInfos.salesPersonId" id="CustomerForm-salesPersonId" name="salesPersonId">
								<j-search-select v-model:value="formData.salesPersonId" dict="f_sales_person,name,id"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="对接职位" v-bind="validateInfos.salesPositionId" id="CustomerForm-salesPositionId" name="salesPositionId">
								<j-search-select disabled v-model:value="formData.salesPositionId" dict="f_sales_position,position_name,id" placeholder="请输入对接职位"  allow-clear ></j-search-select>
							</a-form-item>
						</a-col>
<!--						<a-col :span="24">-->
<!--							<a-form-item label="是否本周新增" v-bind="validateInfos.isNewWeek" id="CustomerForm-isNewWeek" name="isNewWeek">-->
<!--								<j-dict-select-tag v-model:value="formData.isNewWeek" dictCode="yn" placeholder="请选择是否本周新增" disabled allow-clear />-->
<!--							</a-form-item>-->
<!--						</a-col>-->
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, watch} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
    import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JAreaLinkage from '/@/components/Form/src/jeecg/components/JAreaLinkage.vue';
    import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../Customer.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import {initDictOptions} from "@/utils/dict";

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true }
  });
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        customerName: '',
         fenxiaoNick: '',
        distributorCode: '',
        regionId: '',
        contactName: '',
        contactPhone: '',
        wechatId: '',
        status: undefined,
        cooperationDate: '',
        cooperationDateEnd: '',
        industry: '',
        authChannel: '',
        authCompany: '',
        cooperationType: '',
        cooperationDocs: '',
        paymentMethod: '',
        paymentAccount: '',
        deposit: '',
        salesPersonId: '',
        salesPositionId: '',
        isNewWeek: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    // customerName: [{ required: true, message: '请输入客户名称!'},],
    regionId: [{ required: true, message: '请输入客户区域位置!'},],
    // contactName: [{ required: true, message: '请输入客户负责人姓名!'},],
    status: [{ required: true, message: '请输入合作状态!'},],
    industry: [{ required: true, message: '请输入行业!'},],
    salesPersonId: [{ required: true, message: '请输入对接销售人员!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const formRef = ref();
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });


  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

watch(() => formData.salesPersonId, (newValue) => {
  if (newValue) {
    const dictData = initDictOptions('f_sales_person,position_id,position_id,' + encodeURIComponent(`id = '${newValue}'`))
    dictData.then(res => {
      console.log(res)
      if (res[0]) {
        formData.salesPositionId = res[0].value
      }else {
        formData.salesPositionId = ''
      }

    })
  }
})

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
